<template>
  <div id="FormControls" >
    <el-form :disabled="formStatus !== 'edit'" :model="form" :rules="rules" ref="ruleFormRef" label-width="120px" label-position="top" :validate-on-rule-change="true">
      <template v-for="(data, index) in formList">
        <div class="moveFormModel">
          <el-form-item :prop='data.required ? data.valueName : null' :label='data.name'>
            <component :is="comList[data.componentName]" :formStatus="formStatus" :formData="data" ></component>
          </el-form-item>
        </div>
      </template>
    </el-form>
  </div>
</template>

<script setup name="FormControls">
import { reactive, markRaw, ref, watch, defineEmits } from 'vue'
import comList from '../importChild'
//
const form = ref({})
const formModelList = reactive([])
const ruleFormRef = ref(null)
const props = defineProps({
  formList: {
    type: Array,
    default: () => [],
    required: true
  },
  clickIndex: {
    type: Number,
    default: 0
  },
  disabled: {
    type: Boolean,
    default: false
  },
  formStatus: {
    type: String,
    default: 'edit'
  }
})

console.log(props.formList)
const rules = reactive({})
props.formList.forEach(item => {
  form.value[item.valueName] = item[item.valueName]
  if (item.required) {
    console.log(item)
    rules[item.valueName] = [
      { required: item.required, message: `请输入${item.name}`, trigger: item.trigger }
    ]
  }
})

function backFormData () {
  return form.value
}

function setFormData () {
  console.log(123123123)
}

const submitForm = async () => {
  return await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      return true
    } else {
      console.log('error submit!', fields)
      return false
    }
  })
}

defineExpose({ backFormData, submitForm, setFormData })

watch(props, (newProps, oldProps) => {
  newProps.formList.forEach(item => {
    form.value[item.valueName] = item[item.valueName]
  })
})
</script>

<style scoped lang="scss">
.moveFormModel {
  width: 100%;
  height: auto;
  box-sizing: border-box;
  padding: 10px;
  position: relative;
}

.delOne {
  width: 22px;
  height: 22px;
  right: 10px;
  top: 0;
  //display: none;
  font-size: 16px;
  text-align: center;
  line-height: 22px;
  z-index: 90;
  color: #FFFFFF;
  cursor: pointer;
  position: absolute;
  background-color: #F56C6C;
  border-color: #F56C6C;
}
</style>
